package com.aipartner.service.impl;

import com.aipartner.entity.*;
import com.aipartner.mapper.*;
import com.aipartner.service.CreditsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 积分服务实现类
 *
 * @author AI Partner
 * @since 2025-09-18
 */
@Slf4j
@Service
public class CreditsServiceImpl implements CreditsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CreditsTransactionMapper creditsTransactionMapper;

    @Autowired
    private CreditsPackageMapper creditsPackageMapper;

    @Autowired
    private CreditsOrderMapper creditsOrderMapper;

    @Autowired
    private CreditsConsumptionConfigMapper creditsConsumptionConfigMapper;

    @Override
    public Map<String, Object> getUserCreditsInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }

        Map<String, Object> result = new HashMap<>();
        
        // 获取当前积分
        Long currentCredits = user.getCredits() != null ? user.getCredits() : 0L;
        Long totalCreditsEarned = user.getTotalCreditsEarned() != null ? user.getTotalCreditsEarned() : 0L;
        Long totalCreditsConsumed = user.getTotalCreditsConsumed() != null ? user.getTotalCreditsConsumed() : 0L;

        result.put("total", currentCredits);
        result.put("used", totalCreditsConsumed);
        result.put("remaining", currentCredits);
        result.put("monthlyQuota", currentCredits); // 当前积分作为月度配额显示
        result.put("nextResetDate", "2025-10-18"); // 下次重置日期
        result.put("expireDate", "2025-12-31"); // 过期日期

        return result;
    }

    @Override
    public IPage<CreditsTransaction> getUserCreditsHistory(Long userId, Page<?> page) {
        return creditsTransactionMapper.selectByUserIdPage(page, userId);
    }

    @Override
    public List<CreditsPackage> getCreditsPackages() {
        return creditsPackageMapper.selectAvailablePackages();
    }

    @Override
    @Transactional
    public CreditsOrder createCreditsOrder(Long userId, Long packageId, String paymentMethod) {
        // 获取套餐信息
        CreditsPackage creditsPackage = creditsPackageMapper.selectById(packageId);
        if (creditsPackage == null || creditsPackage.getStatus() != 1) {
            throw new RuntimeException("套餐不存在或已下架");
        }

        // 创建订单
        CreditsOrder order = new CreditsOrder();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setPackageId(packageId);
        order.setPackageName(creditsPackage.getName());
        order.setCreditsAmount(creditsPackage.getCreditsAmount());
        order.setAmount(creditsPackage.getPrice());
        order.setPaidAmount(creditsPackage.getPrice());
        order.setPaymentMethod(paymentMethod);
        order.setStatus("pending");
        order.setExpireTime(LocalDateTime.now().plusHours(1)); // 1小时后过期
        order.setCreditsExpireTime(LocalDateTime.now().plusDays(creditsPackage.getValidityDays()));
        order.setCreateTime(LocalDateTime.now());

        creditsOrderMapper.insert(order);
        return order;
    }

    @Override
    @Transactional
    public boolean processCreditsPaymentSuccess(String orderNo, String transactionId) {
        try {
            // 查询订单
            CreditsOrder order = creditsOrderMapper.selectByOrderNo(orderNo);
            if (order == null) {
                log.error("订单不存在: {}", orderNo);
                return false;
            }

            if (!"pending".equals(order.getStatus())) {
                log.warn("订单状态异常: {} - {}", orderNo, order.getStatus());
                return true; // 如果已经处理过，返回true
            }

            // 更新订单状态
            order.setStatus("paid");
            order.setPaidTime(LocalDateTime.now());
            order.setThirdPartyTransactionId(transactionId);
            creditsOrderMapper.updateById(order);

            // 给用户增加积分
            User user = userMapper.selectById(order.getUserId());
            if (user != null) {
                Long oldCredits = user.getCredits() != null ? user.getCredits() : 0L;
                Long newCredits = oldCredits + order.getCreditsAmount();
                
                user.setCredits(newCredits);
                user.setTotalCreditsEarned((user.getTotalCreditsEarned() != null ? user.getTotalCreditsEarned() : 0L) + order.getCreditsAmount());
                user.setCreditsUpdatedTime(LocalDateTime.now());
                userMapper.updateById(user);

                // 记录积分交易
                CreditsTransaction transaction = new CreditsTransaction();
                transaction.setUserId(order.getUserId());
                transaction.setTransactionType("purchase");
                transaction.setAmount(order.getCreditsAmount());
                transaction.setBalanceBefore(oldCredits);
                transaction.setBalanceAfter(newCredits);
                transaction.setSourceType("purchase");
                transaction.setSourceId(order.getOrderNo());
                transaction.setDescription("购买积分套餐：" + order.getPackageName());
                transaction.setExpireTime(order.getCreditsExpireTime());
                transaction.setStatus("completed");
                transaction.setCreateTime(LocalDateTime.now());
                creditsTransactionMapper.insert(transaction);

                log.info("积分购买成功处理完成 - 用户: {}, 订单: {}, 积分: {}", order.getUserId(), orderNo, order.getCreditsAmount());
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("处理积分购买成功回调失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean consumeCredits(Long userId, Long amount, String serviceType, String sourceId, String description) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }

        Long currentCredits = user.getCredits() != null ? user.getCredits() : 0L;
        if (currentCredits < amount) {
            log.warn("用户积分不足 - 用户: {}, 当前积分: {}, 需要积分: {}", userId, currentCredits, amount);
            return false;
        }

        // 扣减积分
        Long newCredits = currentCredits - amount;
        user.setCredits(newCredits);
        user.setTotalCreditsConsumed((user.getTotalCreditsConsumed() != null ? user.getTotalCreditsConsumed() : 0L) + amount);
        user.setCreditsUpdatedTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 记录积分交易
        CreditsTransaction transaction = new CreditsTransaction();
        transaction.setUserId(userId);
        transaction.setTransactionType("consume");
        transaction.setAmount(-amount); // 负数表示消耗
        transaction.setBalanceBefore(currentCredits);
        transaction.setBalanceAfter(newCredits);
        transaction.setSourceType(serviceType);
        transaction.setSourceId(sourceId);
        transaction.setDescription(description);
        transaction.setStatus("completed");
        transaction.setCreateTime(LocalDateTime.now());
        creditsTransactionMapper.insert(transaction);

        log.info("积分消耗成功 - 用户: {}, 消耗积分: {}, 剩余积分: {}, 服务: {}", userId, amount, newCredits, serviceType);
        return true;
    }

    @Override
    public boolean checkCreditsEnough(Long userId, Long amount) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }
        
        Long currentCredits = user.getCredits() != null ? user.getCredits() : 0L;
        return currentCredits >= amount;
    }

    @Override
    public Long getServiceCreditsCost(String serviceType) {
        return creditsConsumptionConfigMapper.selectCreditsCostByServiceType(serviceType);
    }

    @Override
    public List<Map<String, Object>> getCreditsConsumptionRules() {
        List<CreditsConsumptionConfig> configs = creditsConsumptionConfigMapper.selectActiveConfigs();
        List<Map<String, Object>> rules = new ArrayList<>();
        
        for (CreditsConsumptionConfig config : configs) {
            Map<String, Object> rule = new HashMap<>();
            rule.put("type", config.getServiceType());
            rule.put("name", config.getServiceName());
            rule.put("cost", config.getCreditsCost());
            rule.put("unit", "积分/次");
            rule.put("description", config.getDescription());
            
            // 设置图标
            String icon = "photo-o";
            switch (config.getServiceType()) {
                case "ai_image":
                    icon = "photo-o";
                    break;
                case "ai_video":
                    icon = "video-o";
                    break;
                case "hd_enhance":
                    icon = "diamond-o";
                    break;
            }
            rule.put("icon", icon);
            
            rules.add(rule);
        }
        
        return rules;
    }

    @Override
    @Transactional
    public boolean addCredits(Long userId, Long amount, String sourceType, String sourceId, String description) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }

        Long currentCredits = user.getCredits() != null ? user.getCredits() : 0L;
        
        // 增加积分
        Long newCredits = currentCredits + amount;
        user.setCredits(newCredits);
        user.setTotalCreditsEarned((user.getTotalCreditsEarned() != null ? user.getTotalCreditsEarned() : 0L) + amount);
        user.setCreditsUpdatedTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 记录积分交易
        CreditsTransaction transaction = new CreditsTransaction();
        transaction.setUserId(userId);
        transaction.setTransactionType("earn");
        transaction.setAmount(amount); // 正数表示获得
        transaction.setBalanceBefore(currentCredits);
        transaction.setBalanceAfter(newCredits);
        transaction.setSourceType(sourceType);
        transaction.setSourceId(sourceId);
        transaction.setDescription(description);
        transaction.setStatus("completed");
        transaction.setCreateTime(LocalDateTime.now());
        creditsTransactionMapper.insert(transaction);

        log.info("积分添加成功 - 用户: {}, 添加积分: {}, 新余额: {}, 来源: {}", userId, amount, newCredits, sourceType);
        return true;
    }

    @Override
    @Transactional
    public boolean resetUserCredits(Long userId, Long newAmount) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }

        Long currentCredits = user.getCredits() != null ? user.getCredits() : 0L;
        
        // 重置积分
        user.setCredits(newAmount);
        user.setCreditsUpdatedTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 记录积分交易
        CreditsTransaction transaction = new CreditsTransaction();
        transaction.setUserId(userId);
        transaction.setTransactionType("dev_reset");
        transaction.setAmount(newAmount - currentCredits); // 差值
        transaction.setBalanceBefore(currentCredits);
        transaction.setBalanceAfter(newAmount);
        transaction.setSourceType("dev_test");
        transaction.setSourceId("DEV_RESET_" + System.currentTimeMillis());
        transaction.setDescription("开发测试：重置积分为" + newAmount);
        transaction.setStatus("completed");
        transaction.setCreateTime(LocalDateTime.now());
        creditsTransactionMapper.insert(transaction);

        log.info("积分重置成功 - 用户: {}, 原积分: {}, 新积分: {}", userId, currentCredits, newAmount);
        return true;
    }

    // ==================== 管理端相关方法 ====================
    
    @Override
    public Map<String, Object> getAdminCreditsStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 积分总发放 = 所有正数积分交易的总和
            LambdaQueryWrapper<CreditsTransaction> earnWrapper = new LambdaQueryWrapper<>();
            earnWrapper.in(CreditsTransaction::getTransactionType, "purchase", "earn");
            earnWrapper.eq(CreditsTransaction::getStatus, "completed");
            Long totalCredits = creditsTransactionMapper.selectList(earnWrapper).stream()
                    .mapToLong(CreditsTransaction::getAmount)
                    .sum();
            
            // 积分总消耗 = 所有负数积分交易的绝对值总和
            LambdaQueryWrapper<CreditsTransaction> consumeWrapper = new LambdaQueryWrapper<>();
            consumeWrapper.eq(CreditsTransaction::getTransactionType, "consume");
            consumeWrapper.eq(CreditsTransaction::getStatus, "completed");
            Long totalConsumed = creditsTransactionMapper.selectList(consumeWrapper).stream()
                    .mapToLong(transaction -> Math.abs(transaction.getAmount()))
                    .sum();
            
            // 购买订单数
            Long totalOrders = creditsOrderMapper.selectCount(null);
            
            // 积分收入（已支付订单的总金额）
            LambdaQueryWrapper<CreditsOrder> paidWrapper = new LambdaQueryWrapper<>();
            paidWrapper.eq(CreditsOrder::getStatus, "paid");
            Double totalRevenue = creditsOrderMapper.selectList(paidWrapper).stream()
                    .mapToDouble(order -> order.getAmount().doubleValue())
                    .sum();
            
            stats.put("totalCredits", totalCredits);
            stats.put("totalConsumed", totalConsumed);
            stats.put("totalOrders", totalOrders);
            stats.put("totalRevenue", totalRevenue);
            
        } catch (Exception e) {
            log.error("获取管理端积分统计失败", e);
            stats.put("totalCredits", 0L);
            stats.put("totalConsumed", 0L);
            stats.put("totalOrders", 0L);
            stats.put("totalRevenue", 0.0);
        }
        
        return stats;
    }
    
    @Override
    public Page<CreditsTransaction> getAdminCreditsHistory(Page<CreditsTransaction> page, String userId, String transactionType) {
        LambdaQueryWrapper<CreditsTransaction> wrapper = new LambdaQueryWrapper<>();
        
        // 用户ID筛选
        if (userId != null && !userId.trim().isEmpty()) {
            try {
                wrapper.eq(CreditsTransaction::getUserId, Long.valueOf(userId.trim()));
            } catch (NumberFormatException e) {
                // ID格式不正确，返回空结果
                return new Page<>(page.getCurrent(), page.getSize());
            }
        }
        
        // 交易类型筛选
        if (transactionType != null && !transactionType.trim().isEmpty()) {
            wrapper.eq(CreditsTransaction::getTransactionType, transactionType);
        }
        
        // 按创建时间降序排列
        wrapper.orderByDesc(CreditsTransaction::getCreateTime);
        
        return creditsTransactionMapper.selectPage(page, wrapper);
    }
    
    @Override
    public Map<String, Object> getAdminOrderStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 总订单数
            Long totalOrders = creditsOrderMapper.selectCount(null);
            
            // 已支付订单数
            LambdaQueryWrapper<CreditsOrder> paidWrapper = new LambdaQueryWrapper<>();
            paidWrapper.eq(CreditsOrder::getStatus, "paid");
            Long paidOrders = creditsOrderMapper.selectCount(paidWrapper);
            
            // 待支付订单数
            LambdaQueryWrapper<CreditsOrder> pendingWrapper = new LambdaQueryWrapper<>();
            pendingWrapper.eq(CreditsOrder::getStatus, "pending");
            Long pendingOrders = creditsOrderMapper.selectCount(pendingWrapper);
            
            // 总交易金额（已支付订单）
            Double totalAmount = creditsOrderMapper.selectList(paidWrapper).stream()
                    .mapToDouble(order -> order.getAmount().doubleValue())
                    .sum();
            
            stats.put("totalOrders", totalOrders);
            stats.put("paidOrders", paidOrders);
            stats.put("pendingOrders", pendingOrders);
            stats.put("totalAmount", totalAmount);
            
        } catch (Exception e) {
            log.error("获取管理端订单统计失败", e);
            stats.put("totalOrders", 0L);
            stats.put("paidOrders", 0L);
            stats.put("pendingOrders", 0L);
            stats.put("totalAmount", 0.0);
        }
        
        return stats;
    }
    
    @Override
    public Page<CreditsOrder> getAdminOrderList(Page<CreditsOrder> page, String orderNo, String userId, String orderType, String status) {
        LambdaQueryWrapper<CreditsOrder> wrapper = new LambdaQueryWrapper<>();
        
        // 订单号筛选
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            wrapper.like(CreditsOrder::getOrderNo, orderNo.trim());
        }
        
        // 用户ID筛选
        if (userId != null && !userId.trim().isEmpty()) {
            try {
                wrapper.eq(CreditsOrder::getUserId, Long.valueOf(userId.trim()));
            } catch (NumberFormatException e) {
                // 如果用户ID格式不正确，返回空结果
                return new Page<>(page.getCurrent(), page.getSize());
            }
        }
        
        // 订单类型筛选（暂时只有积分订单）
        if (orderType != null && !orderType.trim().isEmpty()) {
            // 这里可以根据实际需求扩展
        }
        
        // 订单状态筛选
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq(CreditsOrder::getStatus, status.trim());
        }
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(CreditsOrder::getCreateTime);
        
        return creditsOrderMapper.selectPage(page, wrapper);
    }
    
    @Override
    public boolean cancelOrder(Long orderId) {
        try {
            CreditsOrder order = creditsOrderMapper.selectById(orderId);
            if (order == null) {
                log.warn("订单不存在: {}", orderId);
                return false;
            }
            
            // 只有待支付状态的订单才能取消
            if (!"pending".equals(order.getStatus())) {
                log.warn("订单状态不允许取消: {}, status: {}", orderId, order.getStatus());
                return false;
            }
            
            // 更新订单状态为已取消
            CreditsOrder updateOrder = new CreditsOrder();
            updateOrder.setId(orderId);
            updateOrder.setStatus("cancelled");
            updateOrder.setUpdateTime(LocalDateTime.now());
            
            return creditsOrderMapper.updateById(updateOrder) > 0;
            
        } catch (Exception e) {
            log.error("取消订单失败: {}", orderId, e);
            return false;
        }
    }
    
    @Override
    public boolean refundOrder(Long orderId, String reason, BigDecimal refundAmount) {
        try {
            CreditsOrder order = creditsOrderMapper.selectById(orderId);
            if (order == null) {
                log.warn("订单不存在: {}", orderId);
                return false;
            }
            
            // 只有已支付状态的订单才能退款
            if (!"paid".equals(order.getStatus())) {
                log.warn("订单状态不允许退款: {}, status: {}", orderId, order.getStatus());
                return false;
            }
            
            // 验证退款金额
            if (refundAmount == null || refundAmount.compareTo(BigDecimal.ZERO) <= 0 || 
                refundAmount.compareTo(order.getAmount()) > 0) {
                log.warn("退款金额无效: {}, 订单金额: {}", refundAmount, order.getAmount());
                return false;
            }
            
            // 更新订单状态为已退款
            CreditsOrder updateOrder = new CreditsOrder();
            updateOrder.setId(orderId);
            updateOrder.setStatus("refunded");
            updateOrder.setUpdateTime(LocalDateTime.now());
            
            boolean orderUpdated = creditsOrderMapper.updateById(updateOrder) > 0;
            
            if (orderUpdated) {
                // 退还积分给用户（如果订单已经发放过积分）
                try {
                    // 获取用户当前积分
                    User user = userMapper.selectById(order.getUserId());
                    if (user != null) {
                        // 扣减用户积分（相当于退还）
                        Long creditsToDeduct = order.getCreditsAmount();
                        if (creditsToDeduct != null && creditsToDeduct > 0) {
                            // 检查用户积分是否足够扣减
                            if (user.getCredits() >= creditsToDeduct) {
                                user.setCredits(user.getCredits() - creditsToDeduct);
                                userMapper.updateById(user);
                                
                                // 记录积分交易
                                CreditsTransaction transaction = new CreditsTransaction();
                                transaction.setUserId(order.getUserId());
                                transaction.setAmount(-creditsToDeduct);
                                transaction.setBalanceBefore(user.getCredits() + creditsToDeduct);
                                transaction.setBalanceAfter(user.getCredits());
                                transaction.setTransactionType("refund");
                                transaction.setSourceType("refund");
                                transaction.setSourceId(order.getOrderNo());
                                transaction.setDescription("订单退款扣减积分：" + reason);
                                transaction.setStatus("completed");
                                transaction.setCreateTime(LocalDateTime.now());
                                
                                creditsTransactionMapper.insert(transaction);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("退款时处理积分失败: {}", orderId, e);
                    // 积分处理失败不影响订单状态更新
                }
                
                log.info("订单退款成功: {}, 原因: {}, 金额: {}", orderId, reason, refundAmount);
                return true;
            }
            
            return false;
            
        } catch (Exception e) {
            log.error("订单退款失败: {}", orderId, e);
            return false;
        }
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "CRD" + System.currentTimeMillis() + String.format("%03d", new Random().nextInt(1000));
    }
    
    // ==================== 积分套餐管理方法实现 ====================
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createCreditsPackage(CreditsPackage creditsPackage) {
        try {
            log.info("开始创建积分套餐: {}", creditsPackage.getName());
            creditsPackage.setCreateTime(LocalDateTime.now());
            creditsPackage.setUpdateTime(LocalDateTime.now());
            if (creditsPackage.getStatus() == null) {
                creditsPackage.setStatus(1); // 默认上架
            }
            
            int result = creditsPackageMapper.insert(creditsPackage);
            log.info("创建积分套餐完成: {}, 影响行数: {}, 套餐ID: {}", creditsPackage.getName(), result, creditsPackage.getId());
            
            if (result > 0) {
                // 验证插入是否成功
                CreditsPackage inserted = creditsPackageMapper.selectById(creditsPackage.getId());
                log.info("验证插入结果 - 套餐: {}", inserted != null ? inserted.getName() : "null");
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("创建积分套餐失败: {}", creditsPackage.getName(), e);
            throw new RuntimeException("创建积分套餐失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCreditsPackage(Long packageId, CreditsPackage creditsPackage) {
        try {
            log.info("开始更新积分套餐 ID: {}, 名称: {}", packageId, creditsPackage.getName());
            
            // 先查询原数据
            CreditsPackage original = creditsPackageMapper.selectById(packageId);
            if (original == null) {
                log.warn("要更新的积分套餐不存在: {}", packageId);
                return false;
            }
            
            creditsPackage.setId(packageId);
            creditsPackage.setUpdateTime(LocalDateTime.now());
            // 保持原创建时间
            creditsPackage.setCreateTime(original.getCreateTime());
            
            int result = creditsPackageMapper.updateById(creditsPackage);
            log.info("更新积分套餐完成: ID={}, 影响行数: {}", packageId, result);
            
            if (result > 0) {
                // 验证更新是否成功
                CreditsPackage updated = creditsPackageMapper.selectById(packageId);
                log.info("验证更新结果 - 套餐名称: {} -> {}", original.getName(), updated.getName());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新积分套餐失败: {}", packageId, e);
            throw new RuntimeException("更新积分套餐失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    @Transactional
    public boolean deleteCreditsPackage(Long packageId) {
        try {
            int result = creditsPackageMapper.deleteById(packageId);
            log.info("删除积分套餐: {}, 结果: {}", packageId, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("删除积分套餐失败: {}", packageId, e);
            return false;
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCreditsPackageStatus(Long packageId, Integer status) {
        try {
            log.info("开始更新积分套餐状态: ID={}, 新状态={}", packageId, status);
            
            // 先查询原数据
            CreditsPackage original = creditsPackageMapper.selectById(packageId);
            if (original == null) {
                log.warn("要更新状态的积分套餐不存在: {}", packageId);
                return false;
            }
            
            CreditsPackage creditsPackage = new CreditsPackage();
            creditsPackage.setId(packageId);
            creditsPackage.setStatus(status);
            creditsPackage.setUpdateTime(LocalDateTime.now());
            
            int result = creditsPackageMapper.updateById(creditsPackage);
            log.info("更新积分套餐状态完成: ID={}, 状态 {} -> {}, 影响行数: {}", 
                     packageId, original.getStatus(), status, result);
            
            if (result > 0) {
                // 验证更新是否成功
                CreditsPackage updated = creditsPackageMapper.selectById(packageId);
                log.info("验证状态更新结果: {}", updated.getStatus().equals(status) ? "成功" : "失败");
                return updated.getStatus().equals(status);
            }
            return false;
        } catch (Exception e) {
            log.error("更新积分套餐状态失败: {}", packageId, e);
            throw new RuntimeException("更新积分套餐状态失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<CreditsPackage> getAdminCreditsPackages() {
        try {
            log.info("🎯 [Service] CreditsServiceImpl.getAdminCreditsPackages() 被调用");
            // 管理端需要获取所有套餐，不论状态
            LambdaQueryWrapper<CreditsPackage> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByAsc(CreditsPackage::getSortOrder)
                   .orderByAsc(CreditsPackage::getId);
            List<CreditsPackage> packages = creditsPackageMapper.selectList(wrapper);
            log.info("🎯 [Service] 管理端获取积分套餐列表完成，共{}个套餐", packages.size());
            
            if (!packages.isEmpty()) {
                log.info("🎯 [Service] 第一个套餐: {} (状态: {})", packages.get(0).getName(), packages.get(0).getStatus());
            }
            
            return packages;
        } catch (Exception e) {
            log.error("🎯 [Service] 获取管理端积分套餐失败", e);
            return new ArrayList<>();
        }
    }
    
    // ==================== 积分消耗规则管理方法实现 ====================
    
    @Override
    @Transactional
    public boolean createCreditsRule(String type, String name, Long cost, String unit, String description) {
        try {
            CreditsConsumptionConfig rule = new CreditsConsumptionConfig();
            rule.setServiceType(type);
            rule.setServiceName(name);
            rule.setCreditsCost(cost);
            rule.setDescription(description);
            rule.setIsActive(true); // 默认启用
            rule.setCreateTime(LocalDateTime.now());
            rule.setUpdateTime(LocalDateTime.now());
            
            int result = creditsConsumptionConfigMapper.insert(rule);
            log.info("创建积分消耗规则: {}, 结果: {}", name, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("创建积分消耗规则失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updateCreditsRule(Long ruleId, String type, String name, Long cost, String unit, String description) {
        try {
            CreditsConsumptionConfig rule = new CreditsConsumptionConfig();
            rule.setId(ruleId);
            rule.setServiceType(type);
            rule.setServiceName(name);
            rule.setCreditsCost(cost);
            rule.setDescription(description);
            rule.setUpdateTime(LocalDateTime.now());
            
            int result = creditsConsumptionConfigMapper.updateById(rule);
            log.info("更新积分消耗规则: {}, 结果: {}", ruleId, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("更新积分消耗规则失败: {}", ruleId, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean deleteCreditsRule(Long ruleId) {
        try {
            int result = creditsConsumptionConfigMapper.deleteById(ruleId);
            log.info("删除积分消耗规则: {}, 结果: {}", ruleId, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("删除积分消耗规则失败: {}", ruleId, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updateCreditsRuleStatus(Long ruleId, Integer status) {
        try {
            CreditsConsumptionConfig rule = new CreditsConsumptionConfig();
            rule.setId(ruleId);
            rule.setIsActive(status == 1);
            rule.setUpdateTime(LocalDateTime.now());
            
            int result = creditsConsumptionConfigMapper.updateById(rule);
            log.info("更新积分消耗规则状态: {}, 状态: {}, 结果: {}", ruleId, status, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("更新积分消耗规则状态失败: {}", ruleId, e);
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getAllCreditsRules() {
        try {
            List<CreditsConsumptionConfig> configs = creditsConsumptionConfigMapper.selectList(
                new LambdaQueryWrapper<CreditsConsumptionConfig>()
                    .orderByDesc(CreditsConsumptionConfig::getCreateTime)
            );
            
            List<Map<String, Object>> rules = new ArrayList<>();
            for (CreditsConsumptionConfig config : configs) {
                Map<String, Object> rule = new HashMap<>();
                rule.put("id", config.getId());
                rule.put("type", config.getServiceType());
                rule.put("name", config.getServiceName());
                rule.put("cost", config.getCreditsCost());
                rule.put("unit", "积分/次");
                rule.put("description", config.getDescription());
                rule.put("status", config.getIsActive() ? 1 : 0);
                rule.put("createTime", config.getCreateTime());
                rule.put("updateTime", config.getUpdateTime());
                rules.add(rule);
            }
            
            return rules;
        } catch (Exception e) {
            log.error("获取所有积分消耗规则失败", e);
            return new ArrayList<>();
        }
    }
    
    // ==================== 同步小程序数据库实现 ====================
    
    @Override
    public boolean syncCreditsPackagesToMiniProgram() {
        try {
            // 这里应该调用小程序数据库同步接口
            // 由于没有具体的小程序数据库配置，这里只是记录日志
            List<CreditsPackage> packages = getAdminCreditsPackages();
            log.info("开始同步积分套餐到小程序数据库，共{}个套餐", packages.size());
            
            // TODO: 实际的同步逻辑
            // 可以通过HTTP请求调用小程序后端API，或者直接操作小程序数据库
            
            log.info("积分套餐同步完成");
            return true;
        } catch (Exception e) {
            log.error("同步积分套餐到小程序数据库失败", e);
            return false;
        }
    }
    
    @Override
    public boolean syncCreditsRulesToMiniProgram() {
        try {
            // 这里应该调用小程序数据库同步接口
            List<Map<String, Object>> rules = getAllCreditsRules();
            log.info("开始同步积分消耗规则到小程序数据库，共{}个规则", rules.size());
            
            // TODO: 实际的同步逻辑
            // 可以通过HTTP请求调用小程序后端API，或者直接操作小程序数据库
            
            log.info("积分消耗规则同步完成");
            return true;
        } catch (Exception e) {
            log.error("同步积分消耗规则到小程序数据库失败", e);
            return false;
        }
    }
}
